/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-10-09 15:03:16
 * @LastEditTime: 2022-10-24 16:52:58
 */
import { Button, Checkbox, Descriptions, Table, Tabs, Badge, Result } from 'antd';
import { PieChartOutlined, CloseCircleTwoTone, FileDoneOutlined } from '@ant-design/icons';
import styles from '../styles/result.module.scss';
import classNames from 'classnames/bind';
import { debounce } from 'lodash-es';
import { Key, useEffect, useState } from 'react';
import { render } from '@testing-library/react';
import { indexOf } from '@/mock/user';

const { TabPane } = Tabs;

const cx = classNames.bind(styles);
interface IOriginalEntryErrorProps {
  onOpen: any;
  detectionResultArchives: Array<any>;
}
const OriginalEntryError = (props: IOriginalEntryErrorProps) => {
  const { onOpen, detectionResultArchives } = props;
  const [result, setResult] = useState<any>({ checkResult: true });
  const [changeTab, setChangeTab] = useState('');
  const [check, setCheck] = useState(false);
  const [resultDatas, setResultDatas] = useState(detectionResultArchives);
  const [resultData, setResultData] = useState([]);
  const [iCurrent, setICurrent] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>();
  const columns = [
    {
      title: '序号',
      key: 'key',
      dataIndex: 'key',
      width: 50
    },
    {
      title: '档号',
      dataIndex: ['entryMap', '档号'],
      key: 'reference'
    },
    {
      title: '题名',
      dataIndex: ['entryMap', '题名'],
      key: 'title'
    },
    {
      title: '状态',
      key: 'checkResult',
      dataIndex: 'checkResult',
      render: (integrity: any) => (integrity ? '成功' : '失败'),
      width: 50
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => {
        return record.checkResult ? (
          <Button type="link" disabled>
            查看
          </Button>
        ) : (
          <Button
            type="link"
            onClick={() => {
              setResult(record);
              setSelectedRowKeys([record.key]);
            }}
          >
            查看
          </Button>
        );
        //
      }
    }
  ];

  const column = [
    {
      title: '序号',
      key: 'key',
      dataIndex: 'key',
      width: 50
    },
    {
      title: '文件名',
      dataIndex: ['entryMap', 'file_name'],
      key: 'fileName'
    },
    {
      title: '状态',
      key: 'checkResult',
      dataIndex: 'checkResult',
      render: (integrity: any) => (integrity ? '成功' : '失败'),
      width: 80
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => {
        return record.checkResult ? (
          <Button type="link" disabled>
            查看
          </Button>
        ) : (
          <Button
            type="link"
            onClick={() => {
              setResult(record);
              setSelectedRowKeys([record.key]);
            }}
          >
            查看
          </Button>
        );
        //
      }
    }
  ];

  useEffect(() => {
    if (changeTab !== '') {
      const resultDataList = resultDatas.find(
        (item) => item.levelInfo.level + '' === changeTab
      ).data;
      check
        ? setResultData(resultDataList.filter((item: any) => item.checkResult === false))
        : setResultData(resultDataList);
    }
    setSelectedRowKeys([1]);
  }, [resultDatas, changeTab]);
  /* 判断表格值是否改变 */
  useEffect(() => {
    setResult(resultData[0]);
  }, [resultData]);
  /* detectionResultArchives改变刷新 */
  useEffect(() => {
    setCheck(false);
    setICurrent(1);
    setResultDatas(detectionResultArchives);
    setChangeTab(detectionResultArchives[0].levelInfo.level + '');
    setSelectedRowKeys([1]);
  }, [detectionResultArchives]);

  /* 选择未通过项时触发 */
  const onChange = (event: any) => {
    // 只错误
    setCheck(event.target.checked);

    if (event.target.checked) {
      console.log(event, resultData, event.target.checked);
      setResultData((state: any) => {
        return state.filter((item: any) => item.checkResult === false);
      });
    }
    // 普通
    else {
      setResultData(
        detectionResultArchives.find((item) => item.levelInfo.level + '' === changeTab).data
      );
    }
    console.log(`checked = ${event.target.checked}`);
  };

  const renderTab = (props: any) => {
    return (
      <Badge count={<CloseCircleTwoTone twoToneColor="#eb2f96" />} size="small" offset={[8, 0]}>
        {/* <Button size="small"> {props}</Button> */}
        {props}
      </Badge>
    );
  };

  const slots = (
    <Checkbox onChange={onChange} checked={check}>
      仅查看未通过
    </Checkbox>
  );

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys: number[], selectedRows: any) => {
      console.log(selectedRowKeys, selectedRows);
      setResult(selectedRows[0]);
      setSelectedRowKeys(selectedRowKeys);
    }
  };

  const handleTypeChange = (event: any) => {
    setChangeTab(event);
    console.log(event);
  };

  const onChangeCurrent = (event: any) => {
    console.log(event);
    setICurrent(event);
  };
  return (
    <div className={cx('result-result')}>
      <div className={cx('result-OEE1')}>
        <div className={cx('result-pie')}>
          <div className={cx('result-information')}>检测结果</div>
          <Button type="text" onClick={onOpen}>
            <PieChartOutlined />
            结果统计
          </Button>
        </div>
        <Tabs
          size="small"
          tabBarExtraContent={{ right: slots }}
          onTabClick={handleTypeChange}
          activeKey={changeTab + ''}
        >
          {detectionResultArchives.map((item: any) => (
            // <TabPane tab={renderTab(item.levelInfo.level_name)} key={item.levelInfo.level}>
            <TabPane tab={item.levelInfo.level_name} key={item.levelInfo.level}>
              {item.levelInfo.level === 0 ? (
                <Table
                  size="small"
                  bordered
                  rowKey={'key'}
                  columns={column}
                  dataSource={resultData.map((item: any) => ({
                    ...item,
                    key: resultData.indexOf(item) + 1
                  }))}
                  rowSelection={{ type: 'radio', ...rowSelection }}
                  pagination={{
                    pageSize: 5,
                    defaultCurrent: 1,
                    hideOnSinglePage: true,
                    current: iCurrent,
                    onChange: onChangeCurrent
                  }}
                  scroll={{ y: 240 }}
                />
              ) : (
                <Table
                  size="small"
                  bordered
                  rowKey={'key'}
                  columns={columns}
                  dataSource={resultData.map((item: any) => ({
                    ...item,
                    key: resultData.indexOf(item) + 1
                  }))}
                  rowSelection={{ type: 'radio', ...rowSelection }}
                />
              )}
            </TabPane>
          ))}
        </Tabs>
      </div>
      <div className={cx('result-OEE2')}>
        <Descriptions title={'检测结果'} labelStyle={{ fontWeight: 'bold' }} layout="vertical">
          {result?.checkResult ? (
            <Descriptions.Item span={3}>
              <div style={{ margin: 'auto' }}>
                <Result icon={<FileDoneOutlined />} title="检测通过" />
              </div>
            </Descriptions.Item>
          ) : (
            <>
              {result?.errorMsg.map((item: any) => (
                <Descriptions.Item label={item.name} span={3} key={item.name}>
                  <div>
                    {item.items.map((iitem: any) => (
                      <p key={iitem}>{iitem}</p>
                    ))}
                  </div>
                </Descriptions.Item>
              ))}
            </>
          )}
        </Descriptions>
      </div>
    </div>
  );
};
export default OriginalEntryError;
